<template>
  <div class="table-wrap">
    <div class="table-search">
      <div class="search-wrap">
        <div class="item-wrap">
          <div class="search-item">
            <span class="search-item-prefix">企业查询</span>
            <Input placeholder="输入关键字查询" v-model:value="pageRequest.search!.name" style="width: 215px"
              allowClear></Input>
          </div>
          <div class="search-item">
            <span class="search-item-prefix">最近登录</span>
            <RangePicker :placeholder="['请选择日期', '请选择日期']" style="width: 215px" v-model:value="loginDateRangeValue"
              @change="handleLoginRang" allowClear format="YYYY-MM-DD" />
          </div>
        </div>
        <div class="search-btn">
          <Button type="primary" class="!flex flex-row items-center" @click="getCompanyList">
            <template #icon>
              <SearchOutlined class="!flex" />
            </template>查询
          </Button>
          <Button type="default" @click="handleReset">重置</Button>
        </div>
      </div>

      <div class="select-wrap">
        <div class="select-item" v-if="statesType">
          <span class="search-item-prefix">企业状态</span>
          <div class="tags-item">
            <CheckableTag v-for="(item, index) in statesType" :key="index" :checked="item.checked"
              @click="() => handlerLoginState(item.value)">
              {{ item.label }} {{ item.count ? `(${item.count})` : '' }} </CheckableTag>
          </div>
        </div>
        <div class="select-item" v-if="createTimeType">
          <span class="search-item-prefix">注册时间</span>
          <div class="tags-item">
            <CheckableTag v-for="(item, index) in createTimeType" :key="index" :checked="item.checked"
              @click="() => handlerCreateState(item.value)">
              {{ item.label }} {{ item.count ? `(${item.count})` : '' }} </CheckableTag>
          </div>
        </div>
      </div>

      <div class="more-item-wrap">
        <span class="search-item-prefix">更多筛选</span>
        <TreeSelect v-model:value="pageRequest.search!.industryId" style="width: 200px"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="所属行业" allow-clear
          :tree-data="industryList" :field-names="{
            children: 'children',
            label: 'name',
            value: 'id',
          }">
        </TreeSelect>
        <TreeSelect v-model:value="pageRequest.search!.regionId" style="width: 200px"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="所属城市" allow-clear
          :tree-data="regionList" :field-names="{
            children: 'children',
            label: 'name',
            value: 'id',
          }">
        </TreeSelect>
      </div>
    </div>

    <div class="table-content">
      <div class="table-add-btn">
        <span>共{{ accountDatasource && accountDatasource.count }}个企业</span>
        <Button type="primary" @click="handleAdd()" class="!flex flex-row items-center">
          <template #icon>
            <PlusOutlined class="!flex" />
          </template>添加企业</Button>
      </div>

      <Table :columns="enterpriseColumns" :data-source="accountDatasource && accountDatasource.items" :pagination="{
        pageSize: pageRequest.page!.pageSize,
        total: accountDatasource?.count,
        pageSizeOptions: pageSizeOptions,
        showSizeChanger: true,
      }" row-key="id" :loading="loading" @change="onChange">
        <template #bodyCell="{ column, record }">

          <template v-if="column.key === 'fullName'">
            <div class="cursor-pointer text-[#0960bd]" @click="handleDrawerOpen(record)">
              {{ record.fullName ?? '--' }}
            </div>
          </template>

          <template v-if="column.key === 'stateName'">
            <div v-if="record.state != 0" :class="`cursor-pointer ${record.state === 1 ? 'text-[#ffaf30]' : 'text-[#ff4d4f]'}`" @click="handleState(record)">
              {{ record.stateName.name ?? '--' }}
            </div>
            <span v-else class="text-[#51bb50]"> {{ record.stateName.name ?? '--' }}</span>
          </template>

          <template v-if="column.key === 'createTime'">
            <span>{{ convertTime(record.createTime, 'YYYY-MM-DD HH:mm') }}</span>
          </template>

          <template v-if="column.key === 'lastLoginTime'">
            <span>{{ record.lastLoginTime ?? '--' }}</span>
          </template>

          <template v-if="column.key === 'action'">
            <Button class="!px-0 !mr-6" type="link" @click="handleAdd(record)">编辑</Button>
            <Button v-if="record.state !== 0" class="!px-0 !mr-6" type="link" @click="handleState(record)">审核</Button>
            <Popconfirm v-if="record.state === 0 || record.state === 9"
              :title="`确认${record.state === 0 ? '下架' : '上架'}企业吗?`" ok-text="确认" cancel-text="取消"
              @confirm="handleStateComfire(record)">
              <Button class="!px-0 !mr-6" type="link" @click="">{{ record.state === 0 ? '下架' : record.state === 9 ? '上架'
                : '' }}</Button>
            </Popconfirm>
          </template>
        </template>
      </Table>
    </div>
    <DrawerModal ref="detailRef" @ok="getCompanyList" />
    <AddEnterpriseModal ref="addRef" @ok="getCompanyList" />
    <StateModal ref="stateRef" @ok="getCompanyList" />
  </div>
</template>

<script lang="ts" setup name="Enterprise">
import { ref } from 'vue'
import { SearchOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { enterpriseColumns } from './index'
import { Input, RangePicker, Button, Table, TreeSelect, Tag, message, Popconfirm } from 'ant-design-vue'
import { Dayjs } from 'dayjs';
import DrawerModal from './DrawerModal.vue'
import AddEnterpriseModal from './AddEnterpriseModal.vue';
import StateModal from './StateModal.vue';
import { CompanyApi, CompanyQueryRequestPageSearchRequest, CompanyQueryResult, CompanyQueryResultCompanyQueryStatResultPageListModel, HomeApi, Industry, Int32SelectCheckableTag, Region } from '@/api';
import { convertTimeChange, convertTime, buildTree } from '@/utils/queryConversion';

const { CheckableTag } = Tag;

type RangeValue = [Dayjs, Dayjs] | [string, string] | undefined;

const loading = ref(false)
const pageRequest = reactive<CompanyQueryRequestPageSearchRequest>({
  page: {
    pageIndex: 1,
    pageSize: 20,
  },
  search: {},
  sort: {
    field: '',
    reverse: true,
  },
});
const pageSizeOptions = ref<string[]>(['5', '10', '20', '50', '100']);
const accountDatasource = ref<CompanyQueryResultCompanyQueryStatResultPageListModel>()
// 日期范围选择
const createDateRangeValue = ref<RangeValue>();
// 日期范围选择
const loginDateRangeValue = ref<RangeValue>();
// 注册时间
const createTimeType = ref<Int32SelectCheckableTag[] | undefined>();
// 登录时间
const statesType = ref<Int32SelectCheckableTag[] | undefined>();
// 详情
const detailRef = ref();
// 添加企业
const addRef = ref();
// 审核
const stateRef = ref();
// 行政区域
const regionList = ref<Region[]>([]);
const industryList = ref<Industry[]>([])

function handleReset() {
  createDateRangeValue.value = undefined;
  loginDateRangeValue.value = undefined;
  pageRequest.search = {}
  getCompanyList();
}

// 获取机构列表
const getCompanyList = async () => {
  loading.value = true;
  try {
    let res = await CompanyApi.companyCompanylist(pageRequest);
    accountDatasource.value = res;
    createTimeType.value = res?.extend?.createTimes;
    statesType.value = res?.extend?.states;
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
}

// 获取行政区域列表
const getRegionList = async () => {
  const res = await HomeApi.getregionlist();
  regionList.value = res;
}

// 获取行业列表
const getIndustryList = async () => {
  const res = await HomeApi.getindustrylist();
  industryList.value = buildTree(res);
}

function handleLoginRang() {
  let time = convertTimeChange(loginDateRangeValue.value, 'YYYY-MM-DD');
  pageRequest.search!.loginTimeStart = time.startTime;
  pageRequest.search!.loginTimeEnd = time.endTime;
}

// 注册时间
function handlerCreateState(id?: number) {
  pageRequest.search!.createTimeType = id && id >= 0 ? id: undefined;
  getCompanyList();
}

function handlerLoginState(id?: number) {
  pageRequest.search!.state = id && id >= 0 ? id: undefined;
  getCompanyList();
}

onMounted(() => {
  getCompanyList();
  getRegionList();
  getIndustryList();
})

// 侧边抽屉详情
const handleDrawerOpen = (data: CompanyQueryResult) => {
  detailRef.value.handleOpen(data);
}

// 翻页和参数筛选
function onChange(pagination: any, filters: any, sorter: any,) {
  pageRequest.page!.pageIndex = pagination.current;
  pageRequest.page!.pageSize = pagination.pageSize;

  pageRequest.sort!.field = sorter.order ? sorter.field : '';
  pageRequest.sort!.reverse = sorter.order == 'descend';
  getCompanyList();
}

// 添加企业
function handleAdd(data?: CompanyQueryResult) {
  if (data) {
    addRef.value.handleOpen(data);
  } else {
    addRef.value.handleOpen();
  }
}

// 审核
function handleState(data: CompanyQueryResult) {
  if (data.state === 0) return;
  stateRef.value.handleOpen(data)
}

// 上下架
async function handleStateComfire(data: CompanyQueryResult) {
  loading.value = true;
  try {
    if (data.state === 0) {
      await CompanyApi.companyCompanystateupdate(data.id!.toString(), '9');
      message.success('下架成功')

    } else if (data.state === 9) {
      await CompanyApi.companyCompanystateupdate(data.id!.toString(), '0');
      message.success('上架成功')
    }
    getCompanyList();
  } catch (error) { } finally {
    loading.value = false;
  }
}
</script>

<style lang="less" scoped></style>